/**
 * chrome v8 实现
 */
/*
// ECMA 262 - 15.8.2.14
	var rngstate;  // Initialized to a Uint32Array during genesis.
	function MathRandom() {
		var r0 = (MathImul(18030, rngstate[0] & 0xFFFF) + (rngstate[0] >>> 16)) | 0;
		rngstate[0] = r0;
		var r1 = (MathImul(36969, rngstate[1] & 0xFFFF) + (rngstate[1] >>> 16)) | 0;
		rngstate[1] = r1;
		var x = ((r0 << 16) + (r1 & 0xFFFF)) | 0;
		// Division by 0x100000000 through multiplication by reciprocal.
		return (x < 0 ? (x + 0x100000000) : x) * 2.3283064365386962890625e-10;
	} 
*/

export function generateArray(start, end) {
  return Array.from(new Array(end + 1).keys()).slice(start);
}

/**
 * 取范围内随机整数
 * @param {number} minNum
 * @param {number} maxNum
 */
export function randomNum(minNum = 1, maxNum) {
  return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
}

/**
 * 单次抽奖
 * @param {number} total 总人数
 * @param {array} excludeNums 已中奖
 * @param {number} count 本次抽取人数
 * @param {object} presetWinners 预设中奖
 * @param {string} currentPrize 当前奖项
 */
export const luckydrawHandler = (
  total,
  excludeNums,
  count,
  presetWinners,
  currentPrize,
  excludedList = {}
) => {
  // 检查是否有预设中奖者
  const presetNumbers = Object.entries(presetWinners || {})
    .filter(([, prizes]) => prizes.includes(currentPrize))
    .map(([number]) => Number(number));

  if (presetNumbers.length > 0) {
    // 如果有预设中奖者,优先返回预设中奖者
    const availablePreset = presetNumbers.filter(
      num => !excludeNums.includes(num)
    );
    if (availablePreset.length > 0) {
      // 如果预设人数超过本次抽取数量,随机抽取部分预设者
      if (availablePreset.length > count) {
        const result = [];
        for (let i = 0; i < count; i++) {
          const randomIndex = Math.floor(
            Math.random() * availablePreset.length
          );
          result.push(availablePreset.splice(randomIndex, 1)[0]);
        }
        return result;
      }
      // 如果预设人数不够,剩余的正常抽取
      const remainCount = count - availablePreset.length;
      if (remainCount > 0) {
        const normalNumbers = normalDraw(
          total,
          [...excludeNums, ...availablePreset],
          remainCount
        );
        return [...availablePreset, ...normalNumbers];
      }
      return availablePreset.slice(0, count);
    }
  }

  // 获取当前奖项的排除名单
  const currentExcluded = excludedList[currentPrize] || [];
  
  // 没有预设中奖者或预设者都已中奖,执行正常抽奖
  return normalDraw(total, [...excludeNums, ...currentExcluded], count);
};

// 正常抽奖逻辑
function normalDraw(total, excludeNums, count) {
  const nums = [];
  while (nums.length < count) {
    const num = Math.floor(Math.random() * total + 1);
    if (!excludeNums.includes(num) && !nums.includes(num)) {
      nums.push(num);
    }
  }
  return nums;
}
